package com.ermao.controller;

import com.ermao.pojo.Account;
import com.ermao.pojo.result.analysis.BillYear;
import com.ermao.service.AnalysisService;
import com.ermao.utils.CheckValidUtils;
import com.ermao.utils.Result;
import com.ermao.utils.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 返回用户的记账分析
 * @author Ermao
 * Date: 2021/8/31 2:03
 */
@RestController
@RequestMapping("/api/v1/users/accounts")
public class AnalysisController {

	private AnalysisService analysisService;

	@Autowired
	public void setAnalysisService(AnalysisService analysisService) {
		this.analysisService = analysisService;
	}

	/**
	 * 用户明细，具体来说就是从起始时间到结束时间内每一天消费的金额
	 * @param userId 用户 id
	 * @param fromTime 起始时间
	 * @param endTime 结束时间
	 * @return 用户明细账单
	 */
	@GetMapping("/details/{userId}")
	public Result getDetailAccountPerDay(@PathVariable("userId") Integer userId,
								   @RequestParam("fromTime")Date fromTime,
								   @RequestParam("endTime")Date endTime) {
		if (!CheckValidUtils.checkFromAndEndTimeValid(fromTime, endTime)) {
			return ResultGenerator.genFailResult("查询明细失败，起始时间不合法");
		}
		List<Account> list = analysisService.selectDetails(userId, fromTime, endTime);
		if (list != null) {
			return ResultGenerator.genSuccessResult(list);
		} else {
			return ResultGenerator.genFailResult("查询明细失败");
		}
	}

	/**
	 * 用户账单，将用户每个月的收支综合计算并存储到一个列表中，整个返回对象还包含年度收支和结余
	 * @param userId 用户 id
	 * @param fromTime 起始时间
	 * @param endTime 结束时间
	 * @return 用户年度账单
	 */
	@GetMapping("/bills/{userId}")
	public Result getBillsAccountPerMonth(@PathVariable("userId") Integer userId,
										 @RequestParam("fromTime")Date fromTime,
										 @RequestParam("endTime")Date endTime
										 ) {
		if (!CheckValidUtils.checkFromAndEndTimeValid(fromTime, endTime)) {
			return ResultGenerator.genFailResult("查询明细失败，起始时间不合法");
		}
		BillYear billYear = analysisService.selectBill(userId, fromTime, endTime);
		if (billYear != null) {
			return ResultGenerator.genSuccessResult(billYear);
		} else {
			return ResultGenerator.genFailResult("查询账单失败");
		}
	}

}
